import { defineStore } from 'pinia';

import {
  getUserInfo, login, loginByPhone, logout,
} from '@/api';
import UserInfoInstance, { UserInfo } from '@/models/UserInfo';
import { deserialize } from '@/plugins/reflect-metadata';
import cookie from '@/utils/cookie';
import redirectToHome from '@/utils/redirectToHome';
import { LoginType } from '@/views/login-page/const';
import LoginInstance from '@/views/login-page/models/LoginInstance';

import useAuthStore from './auth.store';

interface State {
  userInfo: UserInfo;
  isAuthenticated: boolean;
  loading: boolean;
  loginType: number; // 0:手机号登录 1:验证码登录
}

const useUserStore = defineStore('user', {
  state: () => ({
    userInfo: new UserInfo(),
    isAuthenticated: false,
    loading: false,
    loginType: LoginType.LOGIN_BY_PASS,
  }) as State,
  actions: {
    async fetchUserInfo() {
      try {
        const { data } = await getUserInfo();
        const resultData = deserialize(data, UserInfoInstance);
        this.userInfo = resultData.userInfo;
        this.isAuthenticated = true;
        const authStore = useAuthStore();
        authStore.handleAuthInit(this.userInfo);
      } catch (error) {
        //
      }
    },
    async login(params: LoginInstance) {
      try {
        this.loading = true;
        if (this.loginType === LoginType.LOGIN_BY_PASS) {
          const { data } = await login(params);
          cookie.setCookie('token', data.token, 3);
        } else {
          const { data } = await loginByPhone(params);
          cookie.setCookie('token', data.token, 3);
        }
        this.isAuthenticated = true;
        window.location.href = '/';
      } catch (error) {
        //
      } finally {
        this.loading = false;
      }
    },

    async logout() {
      try {
        this.loading = true;
        await logout();
        this.userInfo = new UserInfo();
        this.isAuthenticated = false;
        cookie.removeCookie('token');
        redirectToHome();
      } catch (error) {
        //
      } finally {
        this.loading = false;
      }
    },
  },
});

export default useUserStore;
